package com.zx.ishopping.services.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zx.ishopping.Constants.DeleteConstant;
import com.zx.ishopping.DTO.ProductDto;
import com.zx.ishopping.DTO.ProductPageDTO;
import com.zx.ishopping.entity.Products;
import com.zx.ishopping.exceptions.ProductException;
import com.zx.ishopping.mapper.ProductMapper;
import com.zx.ishopping.results.PageResult;
import com.zx.ishopping.services.ProductService;
import com.zx.ishopping.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.List;

@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    /**
     * 根据分类id查询商品
     * @param categoryId
     * @return
     */
    @Override
    public Long getProductNumByCategoryId(Long categoryId) {
        Long productNum = productMapper.getProductNumByCategoryId(categoryId);
        return productNum;
    }

    /**
     * 分页查询商品
     * @param productPageDTO
     * @return
     */
    @Override
    public PageResult pageQuery(ProductPageDTO productPageDTO) {
        PageHelper.startPage(productPageDTO.getPage(), productPageDTO.getPageSize());
        Page<Products> page = productMapper.pageQuery(productPageDTO);
        long total = page.getTotal();
        List<Products> result = page.getResult();
        PageResult pageResult = new PageResult();
        pageResult.setTotal(total);
        pageResult.setData(result);
        return pageResult; 
    }

    @Override
    public void updateProduct(Products products) {
        
        log.info("修改商品信息：{}",products);
        productMapper.update(products);
    }

    /**
     * 批量删除商品
     * @param ids
     */
    @Override
    public void deleteProduct(List<Long> ids) {
        //判断删除的商品是否为起售，若起售中则无法删除
        
        for (Long id : ids){
            //根据id查询商品
            Products products = productMapper.getById(id);
            if (products.getStatus() == 1){
                throw new ProductException(DeleteConstant.PRODUCT_ACTIVE);
                
            }
        }
        
        productMapper.deleteProduct(ids);
    }

    /**
     * 添加商品
     * @param productDto
     */
    @Override
    public void addProduct(ProductDto productDto) {
        Products products = new Products();
        BeanUtils.copyProperties(productDto,products);
        Long userId = ThreadLocalUtil.get();
        products.setCreateUser(userId);
        products.setVersion(BigInteger.valueOf(0));
        productMapper.addProduct(products);
    }

    /**
     * 用户分页查询商品
     * 当key 与 value 均为 null 代表全部商品
     *
     * @param
     * @return
     */
    @Cacheable(
            value = "productList",
            key = "'category:' + (#productPageDTO.categoryId ?: 'all') + " +
                    "'_name:' + (#productPageDTO.name ?: 'all') + " +
                    "'_lastId:' +( #productPageDTO.nextId ?:'0') + " +
                    "'_size:' + #productPageDTO.pageSize"
    )
    @Override
    public PageResult getProductList(ProductPageDTO productPageDTO) {
        log.info("使用深分页查询（游标方式）");
        //深分页查询 ：无法实现跳页，用户时uniapp端，不支持跳页，所以使用深分页查询
        List<Products> result = productMapper.cursorQuery(productPageDTO);

        Long nextCursor = result.isEmpty() ? null : result.get(result.size() - 1).getId();

        PageResult pageResult = new PageResult();
        pageResult.setData(result);
        pageResult.setTotal(result.size()); // 游标分页一般不返回总数，直接返回当前批次大小
        pageResult.setNextCursor(nextCursor); // 额外加一个游标给前端
        return pageResult;
    }

    /**
     * 获取最畅销商品
     * @return
     */
    @Override
    @Cacheable(value = "bestSaleProductList")
    public List<Products> getBestSaleProductList() {
        List<Products> products = productMapper.getBestSaleProductList();
        return products;
        
    }
}
